import { Component, OnInit, Input } from '@angular/core';
import { Assembly, AssemblyStyles, AssemblyValidators } from '../../../fb-design.model'
import { HttpClient } from '@angular/common/http';
import { FormGroup } from '@angular/forms';

@Component({
    selector: 'qk-image',
    template: `
    <div style="display:inline-block">
        <img src="{{assembly.value}}" [ngStyle]="assembly.attributes.style" />
    </div>
    <div id="file_{{assembly.id}}" class="form-assembly-fileupload" style="position:absolute;bottom:0px;right:0px;">
        <p-fileUpload #file  mode="basic" name="file" customUpload="true" (uploadHandler)="onFileUpload($event, file)" maxFileSize="1000000" chooseLabel="点击上传" auto="true">
        </p-fileUpload>
    </div>
    <ng-container [formGroup]="form">
        <input type="hidden" [formControlName]="assembly.id" [(value)]="assembly.value"/>
    </ng-container>
    `,
    styles: [``],
    providers: []
})
export class QkImage implements OnInit {
    @Input() assembly: Assembly;
    @Input() form: FormGroup;
    @Input() mode: number;
    constructor(
        private httpClient: HttpClient
    ) { }

    ngOnInit() {
        if(this.mode == 2){
            if(1 == this.assembly.authCode){//只读
                $("#mask_"+this.assembly.id).css({'z-index': 1, 'opacity': 0.5, 'background-color':'lightgray'});
            }else if(0 == this.assembly.authCode){//没有权限
                $("#mask_"+this.assembly.id).css({'z-index': 1, 'background-color':'lightgray'});
            }
        }

        if (!this.assembly.value) {
            this.assembly.value = "assets/images/form/upload.jpg";
        }

        //设置样式
        setTimeout(() => {
            $("#file_" + this.assembly.id).find(".ui-fileupload-choose").css({
                'height': this.assembly.attributes.height + 'px',
                'width': this.assembly.attributes.width + 'px',
            });
        }, 200)
    }

    ngDoCheck() {
        this.assembly.attributes.refreshStyle();
    }

    onFileUpload(event, file) {
        const formData: FormData = new FormData();
        formData.append('file', event.files[0], event.files[0].name);
        this.httpClient.post('/form/api/value/image/upload', formData).subscribe(resp => {
            this.assembly.value = '/media/api/storage/download?path=' + resp['data'];
            file.clear();
        });
    }
}